// 获取历史信息
var mongoose = require('mongoose');
var stock = require('tushare').stock;
var async = require('async');
// var util = require('../util');
var model = require('../model');

var logger = require('../util/log').getLog('stock-day');

var list = model.list;
var history = model.history;

mongoose.set('debug', false);

var count = 0;

function change2Obj(code, ktype, arr) {
    var obj = {};
    obj.id = code + ':' + arr[0];
    obj.ktype = ktype;
    obj.code = code;
    obj.date = arr[0];
    obj.open = arr[1];
    obj.highest = arr[2];
    obj.close = arr[3];
    obj.lowest = arr[4];
    obj.vol = arr[5];
    obj.priceChange = arr[6];
    obj.changeRate = arr[7];
    obj.ma5 = arr[8];
    obj.ma10 = arr[9];
    obj.ma20 = arr[10];
    obj.vo5 = arr[11];
    obj.vo10 = arr[12];
    obj.vo20 = arr[13];
    obj.tor = arr[14];

    return obj;
}

function change2Line(code, arr) {
    var line = code;
    for (let i = 0, len = arr.length; i < len; i++) {
        line = line + '|' + arr[i];
    }
    return line;
}

function record(code, ktype, callback) {
    let options = {
        code,
        ktype
    };
    stock.getHistory(options).then(({ data }) => {
        if (data && data.record && data.record.length > 0) {
            console.log('code: %s, have %d record!', code, data.record.length);
            let count = 0;
            async.eachLimit(data.record, 3, (his, cb) => {
                let date = his[0];
                let id = code + ':' + date;

                let upsertOpt = { new: true, upsert: true };

                // 检查是否已经有相同的

                upsertData(code, ktype, his, function (err) {
                    if (err) {
                        cb(err);
                    }
                    else {
                        count++;
                        cb();
                    }
                });
            }, err => {
                if (err) return console.log('err: ', err) && callback(err);
                console.log('code: %s, add %d history record!', code, count);
                setTimeout(function () {
                    callback();
                }, 200);
                // callback();
            });
        } else {
            logger.warn('code: %s didn\'t have any records!', code, options);
            setTimeout(function () {
                callback();
            }, 200);
        }
    });
}

function upsertData(code, ktype, data, cb) {
    let date = data[0], id = code + ':' + date;
    history.count({ id, ktype }, (err, count) => {
        if (err) {
            cb(err);
            return;
        }
        // console.log(code, ktype, id, count);
        if (count > 1) {
            history.deleteMany({ id, ktype }, (err, count) => {
                if (err) {
                    cb(err);
                    return;
                }
                console.log('delete ', id, ktype);
                history.create(change2Obj(code, ktype, data), (err, number, raw) => {
                    if (err) {
                        cb(err);
                    }
                    else {
                        cb();
                    }
                });
            });

        }
        else if (count == 1) {
            return cb(); // 有一个的话就不更新了。
            history.update({ id, ktype }, change2Obj(code, ktype, data), (err, number, raw) => {
                if (err) {
                    cb(err);
                }
                else {
                    cb();
                }
            });
        }
        else {
            history.create(change2Obj(code, ktype, data), (err, number, raw) => {
                if (err) {
                    cb(err);
                }
                else {
                    cb();
                }
            });
        }
    });
}

function logFile(code, ktype, cb) {
    let options = {
        code,
        ktype
    };
    stock.getHistory(options).then(({ data }) => {
        count++;
        if (data && data.record && data.record.length > 0) {
            console.log('logFile: %d: logging %s... have %d logs', count, code, data.record.length);
            for (let i = 0, len = data.record.length; i < len; i++) {
                logger.info(change2Line(code, data.record[i]));
            }
            cb();
        }
        else {
            console.log('%s have no records!', code);
            cb();
        }
    });
}

function sync(ktype) {

    let codes = [];

    list.find().sort('code').exec((err, res) => {
        // console.log(res.length);

        for (let stock of res) {
            codes.push(stock.code); // 所有的股票代码
        }

        async.eachLimit(codes, 3, (code, cb) => {
            // console.log({ ktype });
            record(code, ktype, cb);
            // logFile(code, ktype, cb);
        }, err => {
            if (err) return logger.error(err);
            mongoose.disconnect();
            console.log('log end!');
        });
    });
}

exports.sync = sync;

sync('day');